<template>
  <div class="payment-page min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="lg:max-w-[800px] mx-auto">
        <!-- 返回按钮 -->
        <div class="mb-6">
          <el-button
            link
            class="!px-0 !h-auto text-gray-600 hover:text-primary-600 dark:text-gray-400 dark:hover:text-primary-400"
            @click="handleBack"
          >
            <el-icon class="mr-2"><ArrowLeft /></el-icon>
            返回订单列表
          </el-button>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="py-8">
          <el-skeleton :rows="6" animated />
        </div>

        <template v-else>
          <!-- 支付信息卡片 -->
          <div
            class="bg-white dark:bg-gray-800 rounded-lg shadow-sm dark:border dark:border-gray-700 overflow-hidden"
          >
            <!-- 订单状态 -->
            <div
              class="bg-primary-500 dark:bg-primary-600 text-white px-6 py-8 text-center"
            >
              <h2 class="text-2xl font-medium mb-2">等待支付</h2>
              <p class="text-primary-100">
                请在
                <span class="font-medium text-white">{{
                  formatTime(countdown)
                }}</span>
                内完成支付，超时订单将自动取消
              </p>
            </div>

            <!-- 订单信息 -->
            <div class="p-6 space-y-6">
              <!-- 支付金额 -->
              <div class="text-center">
                <div class="text-gray-500 dark:text-gray-400 mb-2">
                  支付金额
                </div>
                <div
                  class="text-4xl font-bold text-primary-600 dark:text-primary-400"
                >
                  ¥{{ orderInfo.payableAmount.toFixed(2) }}
                </div>
              </div>

              <!-- 订单信息 -->
              <div class="border-t border-gray-100 dark:border-gray-700 pt-6">
                <h3 class="text-base font-medium mb-4 dark:text-gray-100">
                  订单信息
                </h3>
                <div class="space-y-3 text-sm">
                  <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400"
                      >订单编号</span
                    >
                    <span class="text-gray-900 dark:text-gray-100 font-mono">{{
                      orderInfo.orderNo
                    }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400"
                      >商品名称</span
                    >
                    <span class="text-gray-900 dark:text-gray-100">{{
                      orderInfo.title
                    }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400"
                      >订单类型</span
                    >
                    <span class="text-gray-900 dark:text-gray-100">{{
                      getOrderTypeText
                    }}</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400"
                      >下单时间</span
                    >
                    <span class="text-gray-900 dark:text-gray-100">{{
                      formatDate(orderInfo.createTime)
                    }}</span>
                  </div>
                  <!-- 特色体验订单信息 -->
                  <template v-if="orderInfo.type === 'experience'">
                    <div class="flex justify-between">
                      <span class="text-gray-500 dark:text-gray-400"
                        >体验日期</span
                      >
                      <span class="text-gray-900 dark:text-gray-100">{{
                        formatDate(orderInfo.booking?.experienceDate)
                      }}</span>
                    </div>
                    <div class="flex justify-between">
                      <span class="text-gray-500 dark:text-gray-400"
                        >参与人数</span
                      >
                      <span class="text-gray-900 dark:text-gray-100"
                        >{{ orderInfo.booking?.participantCount }}人</span
                      >
                    </div>
                  </template>

                  <!-- 导游订单信息 -->
                  <template v-if="orderInfo.type === 'guide'">
                    <div class="flex justify-between">
                      <span class="text-gray-500 dark:text-gray-400"
                        >预约日期</span
                      >
                      <span class="text-gray-900 dark:text-gray-100">{{
                        formatDate(orderInfo.booking?.guideDate)
                      }}</span>
                    </div>
                    <div class="flex justify-between">
                      <span class="text-gray-500 dark:text-gray-400"
                        >开始时间</span
                      >
                      <span class="text-gray-900 dark:text-gray-100">{{
                        orderInfo.booking?.guideTime
                      }}</span>
                    </div>
                    <div class="flex justify-between">
                      <span class="text-gray-500 dark:text-gray-400"
                        >参与人数</span
                      >
                      <span class="text-gray-900 dark:text-gray-100"
                        >{{ orderInfo.booking?.people }}人</span
                      >
                    </div>
                    <div
                      class="flex justify-between"
                      v-if="orderInfo.booking?.routeName"
                    >
                      <span class="text-gray-500 dark:text-gray-400">路线</span>
                      <span class="text-gray-900 dark:text-gray-100">{{
                        orderInfo.booking?.routeName
                      }}</span>
                    </div>
                  </template>
                </div>
              </div>

              <!-- 支付方式 -->
              <div class="border-t border-gray-100 dark:border-gray-700 pt-6">
                <h3 class="text-base font-medium mb-4 dark:text-gray-100">
                  支付方式
                </h3>
                <div class="grid grid-cols-2 gap-4">
                  <div
                    class="payment-method-card"
                    :class="{ 'is-active': paymentMethod === 'wechat' }"
                    @click="selectPaymentMethod('wechat')"
                  >
                    <div class="payment-method-icon wechat">
                      <img
                        src="//res.wx.qq.com/a/wx_fed/assets/res/OTE0YTAw.png"
                        class="w-12 h-12"
                        alt="微信支付"
                      />
                    </div>
                    <span class="mt-2">微信支付</span>
                  </div>
                  <div
                    class="payment-method-card"
                    :class="{ 'is-active': paymentMethod === 'alipay' }"
                    @click="selectPaymentMethod('alipay')"
                  >
                    <div class="payment-method-icon alipay">
                      <img
                        src="//gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*_AS8R7GMzqQAAAAAAAAAAAAAARQnAQ"
                        class="w-12 h-12"
                        alt="支付宝"
                      />
                    </div>
                    <span class="mt-2">支付宝</span>
                  </div>
                </div>
              </div>

              <!-- 支付按钮 -->
              <el-button
                type="primary"
                class="w-full !h-12 text-base font-medium dark:bg-primary-600 dark:border-primary-600 dark:hover:bg-primary-700 dark:hover:border-primary-700"
                :loading="submitting"
                :disabled="!paymentMethod"
                @click="handlePay"
              >
                立即支付
              </el-button>

              <!-- 温馨提示 -->
              <div
                class="text-xs text-gray-400 dark:text-gray-500 leading-relaxed"
              >
                <p>温馨提示：</p>
                <p>1. 请在规定时间内完成支付，超时订单将自动取消</p>
                <p>2. 如遇支付问题，请联系客服 400-xxx-xxxx</p>
                <p>3. 支付成功后将自动跳转订单详情页</p>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 支付二维码弹窗 -->
    <el-dialog
      v-model="showQRCodeDialog"
      :title="paymentMethod === 'wechat' ? '微信扫码支付' : '支付宝扫码支付'"
      width="400px"
      center
      destroy-on-close
      class="payment-dialog"
    >
      <div class="text-center">
        <!-- 支付金额 -->
        <div class="mb-6">
          <div class="text-gray-500 dark:text-gray-400 text-sm mb-1">
            支付金额
          </div>
          <div
            class="text-2xl font-bold text-primary-600 dark:text-primary-400"
          >
            ¥{{ orderInfo.payableAmount.toFixed(2) }}
          </div>
        </div>

        <!-- 二维码 -->
        <div
          class="qrcode-wrapper mx-auto mb-4 p-6 bg-white rounded-lg inline-block"
        >
          <el-image
            :src="qrCodeUrl || getDefaultQRCode()"
            fit="contain"
            class="w-48 h-48"
          />
        </div>

        <!-- 倒计时 -->
        <div class="countdown mb-4 text-sm">
          <span class="text-gray-500 dark:text-gray-400">请在</span>
          <span
            class="mx-1 text-primary-600 dark:text-primary-400 font-medium"
            >{{ formatTime(countdown) }}</span
          >
          <span class="text-gray-500 dark:text-gray-400">内完成支付</span>
        </div>

        <!-- 支付提示 -->
        <div class="text-gray-500 dark:text-gray-400 text-sm space-y-2">
          <p>
            请使用{{
              paymentMethod === "wechat" ? "微信" : "支付宝"
            }}扫描二维码完成支付
          </p>
          <p v-if="paymentMethod === 'wechat'" class="text-xs">
            <el-icon class="mr-1"><InfoFilled /></el-icon>
            请确保手机微信版本已更新至最新版本
          </p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft, InfoFilled } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import axios from "@/api/axios";

const router = useRouter();
const route = useRoute();

// 页面状态
const loading = ref(true);
const submitting = ref(false);
const countdown = ref(900); // 15分钟支付倒计时
const paymentMethod = ref("");
const showQRCodeDialog = ref(false);
const qrCodeUrl = ref("");

// 订单信息
const orderInfo = ref({
  orderNo: "ORDER123456789",
  title: "贵港特色手工艺品等2件商品",
  createTime: new Date(),
  payableAmount: 188.0,
});

// 获取默认二维码（用于演示）
const getDefaultQRCode = () => {
  return paymentMethod.value === "wechat"
    ? "//weixin.qq.com/r/LatxqXXE5WYOrUcL93oH"
    : "//qr.alipay.com/bax05352k4yxbpzglr5m2c4";
};

// 格式化倒计时
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${String(minutes).padStart(2, "0")}:${String(remainingSeconds).padStart(2, "0")}`;
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 选择支付方式
const selectPaymentMethod = (method) => {
  paymentMethod.value = method;
};

// 处理返回
const handleBack = () => {
  router.push("/user/orders");
};

// 处理支付
const handlePay = async () => {
  if (!paymentMethod.value) {
    ElMessage.warning("请选择支付方式");
    return;
  }

  try {
    submitting.value = true;
    
    // 调用获取支付二维码API
    try {
      const response = await axios.post(`/payment/create`, {
        orderId: orderInfo.value.orderNo,
        paymentMethod: paymentMethod.value
      });
      
      if (response && response.qrCodeUrl) {
        qrCodeUrl.value = response.qrCodeUrl;
        showQRCodeDialog.value = true;
        
        // 开始轮询支付状态
        startPollingPaymentStatus();
        return;
      }
    } catch (error) {
      console.error("获取支付二维码API失败:", error);
      // 使用测试数据
    }

    // 使用测试数据
    qrCodeUrl.value = getDefaultQRCode();
    showQRCodeDialog.value = true;

    // 开始轮询支付状态
    startPollingPaymentStatus();
  } catch (error) {
    console.error("获取支付二维码失败:", error);
    ElMessage.error("获取支付二维码失败，请重试");
  } finally {
    submitting.value = false;
  }
};

// 轮询支付状态
let pollingTimer = null;
const startPollingPaymentStatus = () => {
  pollingTimer = setInterval(async () => {
    try {
      // 调用查询支付状态API
      try {
        const response = await axios.get(`/payment/status/${orderInfo.value.orderNo}`);
        
        if (response && response.paid) {
          clearInterval(pollingTimer);
          showQRCodeDialog.value = false;
          ElMessage.success("支付成功");
          
          // 根据订单类型跳转到对应的详情页面
          navigateToOrderDetail(true);
          return;
        }
      } catch (error) {
        console.error("查询支付状态API失败:", error);
        // 使用本地模拟逻辑
      }
      
      // 本地模拟逻辑 - 随机概率支付成功
      const paid = Math.random() > 0.8;
      if (paid) {
        clearInterval(pollingTimer);
        showQRCodeDialog.value = false;
        ElMessage.success("支付成功");

        // 根据订单类型跳转到对应的详情页面
        navigateToOrderDetail(true);
      }
    } catch (error) {
      console.error("查询支付状态失败:", error);
    }
  }, 3000);
};

// 跳转到对应的订单详情页
const navigateToOrderDetail = (paySuccess = false) => {
  const status = paySuccess ? "success" : "failed";
  
  switch (orderInfo.value.type) {
    case "hotel":
      router.push({
        name: "HotelOrderDetail",
        params: { id: orderInfo.value.orderNo },
        query: { status },
      });
      break;
    case "ticket":
      router.push({
        name: "TicketOrderDetail",
        params: { id: orderInfo.value.orderNo },
        query: { status },
      });
      break;
    case "experience":
      router.push({
        name: "ExperienceOrderDetail",
        params: { id: orderInfo.value.orderNo },
        query: { status },
      });
      break;
    case "guide":
      router.push({
        name: "GuideOrderDetail",
        params: { id: orderInfo.value.orderNo },
        query: { status },
      });
      break;
    default:
      router.push({
        name: "OrderDetail",
        params: { id: orderInfo.value.orderNo },
        query: { status },
      });
  }
};

// 倒计时
let countdownTimer = null;
const startCountdown = () => {
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(countdownTimer);
      ElMessage.warning("支付超时，订单已取消");
      router.push("/user/orders");
    }
  }, 1000);
};

// 获取订单类型文本
const getOrderTypeText = computed(() => {
  const typeMap = {
    product: "商品订单",
    hotel: "酒店预订",
    ticket: "门票预订",
    experience: "特色体验",
    guide: "导游预约",
  };
  return typeMap[orderInfo.value.type] || orderInfo.value.type;
});

// 获取订单详情
const fetchOrderDetail = async (orderId) => {
  try {
    loading.value = true;
    
    // 调用获取订单详情API
    try {
      const response = await axios.get(`/orders/${orderId}`);
      
      if (response) {
        // 使用API返回的数据
        orderInfo.value = response;
        return;
      }
    } catch (error) {
      console.error("获取订单详情API失败:", error);
      // 解析URL传递的数据
      const { data } = route.query;
      if (data) {
        const orderData = JSON.parse(decodeURIComponent(data));
        console.log("使用URL传递的订单数据:", orderData);
        orderInfo.value = orderData;
      }
    }
  } catch (error) {
    console.error("加载订单详情失败:", error);
    ElMessage.error(error.message || "加载订单详情失败");
    router.push("/user/orders");
  } finally {
    loading.value = false;
  }
};

// 修改页面加载部分
onMounted(async () => {
  try {
    const { orderId } = route.query;

    if (!orderId) {
      throw new Error("订单参数错误");
    }

    await fetchOrderDetail(orderId);

    // 开始倒计时
    startCountdown();
  } catch (error) {
    console.error("加载订单详情失败:", error);
    ElMessage.error(error.message || "加载订单详情失败");
    router.push("/user/orders");
  } finally {
    loading.value = false;
  }
});

// 组件卸载
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  if (pollingTimer) {
    clearInterval(pollingTimer);
  }
});
</script>

<style lang="scss" scoped>
.payment-page {
  // 支付方式卡片样式
  .payment-method-card {
    @apply flex flex-col items-center justify-center p-6 border-2 border-gray-200 dark:border-gray-700 dark:bg-gray-800 rounded-lg cursor-pointer transition-all duration-200;

    .payment-method-icon {
      @apply relative flex items-center justify-center;

      img {
        @apply w-12 h-12 transition-transform duration-200;
      }

      &.wechat {
        @apply text-[#07C160];
      }

      &.alipay {
        @apply text-[#1677FF];
      }
    }

    span {
      @apply text-gray-600 dark:text-gray-300 font-medium;
    }

    &:hover {
      @apply border-primary-500 dark:border-primary-400 bg-primary-50/10 dark:bg-primary-900/10;

      .payment-method-icon img {
        transform: scale(1.05);
      }

      span {
        @apply text-primary-600 dark:text-primary-400;
      }
    }

    &.is-active {
      @apply border-primary-500 dark:border-primary-400 bg-primary-50/20 dark:bg-primary-900/20;
      box-shadow: 0 0 0 1px theme("colors.primary.500");

      span {
        @apply text-primary-600 dark:text-primary-400;
      }
    }
  }
}

// 支付弹窗样式
.payment-dialog {
  :deep(.el-dialog) {
    @apply dark:bg-gray-800;

    .el-dialog__header {
      @apply border-b border-gray-100 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-700/50 px-6 py-4;
      margin-right: 0;

      .el-dialog__title {
        @apply text-base font-medium dark:text-gray-100;
      }
    }

    .el-dialog__body {
      @apply p-6 dark:text-gray-300;
    }
  }

  .qrcode-wrapper {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    &::after {
      content: "";
      @apply absolute inset-0 border-8 border-white rounded-lg pointer-events-none;
      box-shadow: inset 0 2px 6px rgba(0, 0, 0, 0.1);
    }
  }

  .countdown {
    animation: pulse 2s infinite;
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}
</style>
